package com.ruoyi.common.utils.bootdo;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.ruoyi.project.wx.domain.SetImageUploadDO;
import com.ruoyi.project.wx.service.SetImageUploadService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ImgUpload {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //设置好账号的ACCESS_KEY和SECRET_KEY
    private  String ACCESS_KEY = "";//"l9smDlatZ1TcQlkQPPJG8a1E11bFH7yZLX_20i41";
    private  String SECRET_KEY = "";//"xhHd8NWjSAAwE5DjGZgmv5i2IsDjjxwixpknesMe";
    //要上传的空间
    private  String bucketname = "";

    String BASE_URL = "";//"https://olk8w00m5.qnssl.com/";//"http://oizc6o1am.bkt.clouddn.com/";


    //密钥配置
    private  Auth auth;

    ///////////////////////指定上传的Zone的信息//////////////////
    //第一种方式: 指定具体的要上传的zone
    //注：该具体指定的方式和以下自动识别的方式选择其一即可
    //要上传的空间(bucket)的存储区域为华东时
     Zone z = Zone.zone0();
    //要上传的空间(bucket)的存储区域为华北时
    // Zone z = Zone.zone1();
    //要上传的空间(bucket)的存储区域为华南时
    // Zone z = Zone.zone2();

    //第二种方式: 自动识别要上传的空间(bucket)的存储区域是华东、华北、华南。
    //Zone z = Zone.autoZone();
    Configuration c = new Configuration(z);
    //创建上传对象
    UploadManager uploadManager = new UploadManager(c);

    //构造函数 查询七牛云数据
    public ImgUpload(SetImageUploadService setImageUploadService){
        Map<String,Object> map = new HashMap<String,Object>();
        SetImageUploadDO image = setImageUploadService.list(map).get(0);
        ACCESS_KEY = image.getAccessKey();
        SECRET_KEY = image.getSecretKey();
        bucketname = image.getBucketname();
        BASE_URL = image.getBaseUrl();
        //密钥配置
        auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    }

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken(String path) {
        if (StringUtils.isBlank(path)) {
            path = "IMG";
        }
        return auth.uploadToken(bucketname, null, 3600, new StringMap().put("saveKey", path + "$(etag)$(ext)"));
    }

    public String upload(byte[] data, String fileType) throws IOException {
        String filePath = null;
        try {
            //调用put方法上传
            Response res = uploadManager.put(data, null, getUpToken(fileType));
            //打印返回的信息
            System.out.println(res.bodyString());
            filePath = BASE_URL + res.jsonToMap().get("key").toString();
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            logger.error(r.toString());
        } finally {
            return filePath;
        }
    }

    public String uploadOffice(byte[] data, String fileType) throws IOException {
        String filePath = null;
        try {
            //调用put方法上传
            Response res = uploadManager.put(data, null, getUpToken(fileType),null,"application/vnd.openxmlformats-officedocument.wordprocessingml.document",false);
            //打印返回的信息
            System.out.println(res.bodyString());
            filePath = BASE_URL + res.jsonToMap().get("key").toString();
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息\
            logger.error(r.toString());
        } finally {
            return filePath;
        }
    }public String uploadOfficeDoc(byte[] data, String fileType) throws IOException {
        String filePath = null;
        try {
            //调用put方法上传
            Response res = uploadManager.put(data, null, getUpToken(fileType),null,"application/msword",false);
            //打印返回的信息
            System.out.println(res.bodyString());
            filePath = BASE_URL + res.jsonToMap().get("key").toString();
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息\
            logger.error(r.toString());
        } finally {
            return filePath;
        }
    }

    public Boolean delete(String filePath)throws IOException{
        boolean fla = true;
        c = new Configuration(z);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, c);
        try {
            bucketManager.delete(bucketname, filePath);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            logger.error(ex.response.toString());
            fla = false;
        }
        return fla;
    }
}
